package com.sne.sys.controller;

import com.sne.common.entity.Result;
import com.sne.common.enums.ResultCode;
import com.sne.common.validated.Login;
import com.sne.sys.entity.SysUser;
import com.sne.sys.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 登录，注册，生成token
 * </p>
 *
 * @author fanghh
 * @since 2020/1/7
 */
@Slf4j
@RestController
@RequestMapping
@Api(tags = "登录管理")
public class LoginController {

    @Autowired
    private ISysUserService iSysUserService;

    @Value("${jwt.header}")
    private String tokenHeader;

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Result login(@RequestBody @Validated({Login.class}) SysUser sysUser) {
        Map<String, String> data = new HashMap(8);
        String token = iSysUserService.login(sysUser.getUserName(), sysUser.getPassword());
        data.put("token", token);
        return Result.success(data);
    }

    @ApiOperation(value = "退出")
    @GetMapping("/loginOut")
    public Result loginOut(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        if (token == null) {
            return Result.failed(ResultCode.UNAUTHORIZED);
        }
        iSysUserService.logout(token);
        return Result.success();
    }



}
